package bitcat.chuenyee.dao.provider

import org.apache.ibatis.jdbc.SQL
import kotlin.collections.component1
import kotlin.collections.component2

object DynamicSqlProvider {

    @JvmStatic
    fun insert(params: Map<String, Any>): String {
        val table = params["table"] as String
        val data = params["data"] as Map<String, Any>
        return SQL().apply {
            INSERT_INTO(table)
            data.forEach { (k, _) -> VALUES(k, "#{$k}") }
        }.toString()
    }

    @JvmStatic
    fun select(params: Map<String, Any>): String {
        val table = params["table"] as String
        val conditions = params["conditions"] as? Map<String, Any> ?: emptyMap()
        return SQL().apply {
            SELECT("*")
            FROM(table)
            conditions.forEach { (k, _) -> WHERE("$k = #{conditions.$k}") } // 注意这里
        }.toString()
    }


    @JvmStatic
    fun update(params: Map<String, Any>): String {
        val table = params["table"] as String
        val data = params["data"] as Map<*, *>
        val conditions = params["conditions"] as? Map<String, Any> ?: emptyMap()
        return SQL().apply {
            UPDATE(table)
            data.forEach { (k, _) -> SET("$k = #{data.$k}") }  // 注意这里
            conditions.forEach { (k, _) -> WHERE("$k = #{conditions.$k}") } // 注
        }.toString()
    }


    @JvmStatic
    fun delete(params: Map<String, Any>): String {
        val table = params["table"] as String
        val conditions = params["conditions"] as? Map<String, Any> ?: emptyMap()
        return SQL().apply {
            DELETE_FROM(table)
            conditions.forEach { (k, _) -> WHERE("$k = #{conditions.$k}") } // 注意这里
        }.toString()
    }
}
